<?php
/**
 * Created by PhpStorm.
 * User: shx
 * Date: 2016/11/17
 * Time: 9:42
 */
namespace App\Http\Controllers\Api;

use App\Helpers\Wx;
use App\Model\Users;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class WxEvent extends Controller
{
    private $wx_client;
    private $input;

    public function __construct()
    {
        $this->wx_client = new WX(env('WX_APP_ID'), env('WX_APP_SECRET'));
    }

    public function index(Request $request)
    {
        $this->input = $this->wx_client->getInput($request);
        switch ($this->input->MsgType) {
            case 'event' :
                return $this->eventHandle();
            case 'text' :
                return $this->msgHandle();
            default :
                return '';
        }
    }

    private function eventHandle()
    {
        return $this->{'on'.ucfirst($this->input->Event)}();
    }

    private function msgHandle()
    {
        $msg = trim((string)$this->input->Content);

        switch ($msg) {
            case '账号绑定' :
                $wx_user = $this->getUserInfo();
                $text = $this->bindUser($wx_user);
                $text = $text ? $text : '请先到奇异果聚合注册并绑定微信号。';
                return $this->wx_client->sendText($wx_user['openid'], $text);
        }
        return 'success';
    }

    public function getToken()
    {
        return $this->wx_client->getToken();
    }

    private function onSubscribe()
    {
        $wx_user = $this->getUserInfo();

        $text = "欢迎关注奇异果聚合。\n{$this->bindUser($wx_user)}";

        return $this->wx_client->sendText($wx_user['openid'], $text);
    }

    private function getUserInfo()
    {
        return $this->wx_client->getUserInfo((string)$this->input->FromUserName);
    }

    private function bindUser($wx_user)
    {
        $user = Users::where('unionid', $wx_user['unionid'])->first();
        if ($user) {
            $user->wx_open_id2 = $wx_user['openid'];
            $user->save();
        } else {
            $user = Users::create([
                'binding_weixin' => 1,
                'unionid' => $wx_user['unionid'],
                'wx_open_id2' => $wx_user['openid']
            ]);
        }

        return $user->phone ? "已绑定奇异果账号：{$user->phone}，\n您所关注的主播信息将会及时推送给您。" : "{$user->nickname}";
    }
}